<?php

function get_recruitment_list() {
  // Initialising output
  $output = '';
  // Table header
  $header = array(
    array('data' => '#', 'field' => 'nid', 'sort' => 'desc', 'class' => array('w1')),
    array('data' => 'Job code', 'field' => 'field_job_code_value', 'class' => array('w2')),
    array('data' => 'Job name', 'field' => 'title', 'class' => array('w3')),
    array('data' => 'Province', 'field' => 'name', 'class' => array('w4')),
    array('data' => 'Salary', 'field' => 'field_salary_value', 'class' => array('w5')),
    array('data' => 'Job status', 'field' => 'status', 'class' => array('w6')),
  );
  $result = get_latest_recruiments(NUMBER_ITEM_PAGER_RECRUITMENT, true, true, $header);
  $rows = array();
  if (!empty($result) && count($result) > 0) {
    foreach ($result as $item) {
      $rows[] = array(
        $item['nid'],
        $item['field_job_code_value'],
        '<a href="' . url('node/' . $item['nid']) . '">' . $item['title'] . '</a>',
        $item['name'],
        (is_numeric($item['field_salary_value']) ? $item['field_salary_value'] . t('$') : $item['field_salary_value']),
        ($item['status']) ? t('Open') : t('Close'),
      );
    }
  }

  // Setting the output of the field
  $output = theme_table(
                  array(
                    'header' => $header,
                    'rows' => $rows,
                    'attributes' => array('class' => array('table')),
                    'caption' => '',
                    'colgroups' => array(),
                    'sticky' => '',
                    'empty' => t('There are no content in my system.') // The message to be displayed if table is empty
                  )
          ) . theme('pager');

  if (isset($_GET['page'])) {
    print drupal_json_encode(array('data' => $output));
    die();
  }
  return $output;
}

function apply_cv($nid) {
  global $user;
  $message = t('Your job application fail');
  $status = 'error';
  if (user_is_logged_in()) {
    $nid = base64_decode($nid);
    if (!empty($nid) && is_numeric($nid)) {
      $node = node_load($nid);
      if (!empty($node) && $node->status == 1) {
        $application = get_application($nid, $user->uid);
        $status = 'status';
        //Check user whether apply cv existed
        if (empty($application)) {
          $result = insert_application($nid, $user->uid);
          $message = t('Thanks for your CV application. We will get back to you for further information');
        } else {
          $message = t('Your CV has been applied. Thank you');
        }
      }
    }
  }
  drupal_set_message($message, $status);
  drupal_goto((isset($node) && !empty($node) && $node->status == 1) ? 'node/' . $node->nid : '<front>');
}
